<?php
namespace app\admin\controller;
use think\facade\View;
use think\facade\Session;
use app\admin\model\Admin as AdminModel;
class Login extends Base{

    /**
     * 后台登陆
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            $where = [
                ['username', '=', $this->param['username']],
                ['password', '=', md5($this->param['password'])],
                ['password_true', '=', $this->param['password']],
            ];
            if (!$admin = AdminModel::field('id')->where($where)->find()) {
                return $this->error('用户名或密码错误');
            }
            $admin->save([
                'logintime'     =>  time(),
                'loginip'       =>  $this->request->ip(),
                'token'         =>  md5(time())
            ]);
            Session::set('admin', $admin->toArray());
            $http_referer = 'index/index';
            if(!empty($this->param['http_referer'])&&strpos($this->param['http_referer'],'index/login')===false){
                $http_referer = $this->param['http_referer'];
            }
            return $this->success('登陆成功', $http_referer);
        }
        $parse_url = parse_url($this->request->server('HTTP_REFERER'));
        $http_referer = '';
        if (!empty($parse_url['host']) && $this->request->host() == $parse_url['host']) {
            $http_referer = $this->request->server('HTTP_REFERER');
        }
        return View::fetch('', ['http_referer' => $http_referer]);
    }

    /**
     * 退出登陆
     */
    public function out()
    {
        Session::delete('admin');
        return $this->success('退出成功', 'admin/login/index');
    }
}